#coding=utf-8
#LightCam 查询mongodb
#init by hfh 20150521

import socket,os,time,re
import lc_libs
import multiprocessing,subprocess,traceback
import sys,pymongo,json

if __name__ == "__main__":
	
	lchome=lc_libs.lc_getlchome()
	
	db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)
	
	try:
		db.connect()
	except Exception:
		excinfo=traceback.format_exc()
		print excinfo
		
	Conn=db.getConn()
	if Conn==None:
		print "Can not Connect to the MondbDB"
		exit(0)
	
	length = len(sys.argv)
	if length<3:
		strs="wrong para,please input dbname tablename \n just like: \n LightCamPy lc_query.py lc_alert lc_status"
		#strs="wrong para,please input dbname tablename expr \n just like: \n LightCamPy lc_query.py lc_alert lc_status {\\\"_id\\\":{\\\"\$ne\\\":0}}"
		print strs
		exit(0)
	
	dbname=sys.argv[1]
	tablename=sys.argv[2]
	qryjson=lchome+'/scripts/lc_query.json'
	try:
		qryjson=sys.argv[3]
	except:
		pass
	
	dboper=db.useDatabase(dbname)
	tableoper=db.UseCollection(dboper,tablename)
	
	
	#expr={'session_id':sessionid}
	#sortcont=[("session_id",pymongo.ASCENDING)]
	#expr={'_id':{'$ne':0}}
	expr=json.loads(open(qryjson,'r').read())
	sortcont=[("_id",pymongo.ASCENDING)]
	opts=db.queryData(tableoper,expr,sortcont,0)
	jdata={}
	jdata['rows']=[]
	for line in opts:
		sdata={}
		for key,value in line.items():
			if key=='_id':
				continue
			sdata[key]=value
		jdata['rows'].append(sdata)
	print json.dumps(jdata)
